using MongoDB.Driver;
using Sustainalytics.Synchronization.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sustainalytics.ClientDW.Synchronization.SyncHbaseData
{
    public class SyncCommand
    {
        private readonly CollectionFactory _collectionFactory;
        private readonly ILogger _logger;

        public SyncCommand(CollectionFactory collectionFactory, ILogger logger)
        {
            _collectionFactory = collectionFactory;
            _logger = logger;
        }

        public async Task ExecuteAsync<T>(IEnumerable<T> entities, Func<IMongoCollection<T>, Task> recreateIndexes = null)
        {
            var mongoCollection = _collectionFactory.Get<T>();

            await mongoCollection.Database.DropCollectionAsync(typeof(T).Name);
            _logger.Log($"collection {typeof(T).Name} droped.");

            if (entities != null && entities.Any())
            {
                await mongoCollection.InsertManyAsync(entities);
                _logger.Log($"inserted {entities.Count()} in collection {typeof(T).Name}.");
            }

            if (recreateIndexes != null)
            {
                await recreateIndexes(mongoCollection);
                _logger.Log($" collection {typeof(T).Name} index recreated.");
            }
        }
    }
}
